<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form size="small" :inline="true" @submit.native.prevent>
      <el-form-item label="项目名称">
        <el-input
          v-model="searchForm.project"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          class="button"
          plain
          >查询</el-button
        >
        <el-button
          type="info"
          icon="el-icon-refresh"
          size="mini"
          @click="handleReset"
          class="button"
          plain
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 顶部功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          plain
          @click="handleAdd"
          v-hasPermi="['projectMain_add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="mini"
          plain
          @click="handleDel()"
          :disabled="multiple1"
          v-hasPermi="['projectMain_delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleImport('projectMaintenance')"
          v-hasPermi="['projectMain_upload']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleExport()"
          v-hasPermi="['projectMain_Export']"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <!-- 表 -->
    <el-table
      ref="tableList"
      v-loading="loading"
      :data="tableList"
      border
      :max-height="THeight"
      :stripe="true"
      @selection-change="handleSelectionChange1"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="序号"
        align="center"
        key="Index"
        prop="Index"
        width="100"
      />
      <el-table-column label="项目名称" align="center" prop="project" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="SeeMaintence(scope.row)"
            v-hasPermi="['projectMain_detail']"
            >维护详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDel(scope.row)"
            v-hasPermi="['projectMain_delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination
      :total="total"
      :page.sync="Page.pageNum"
      :limit.sync="Page.pageSize"
      @pagination="getInfo()"
    />
    <!-- 添加1 -->
    <el-dialog
      title="新增"
      :visible.sync="Open1"
      width="380px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="Open1Cancel"
    >
      <el-card>
        <el-form
          ref="diaLogForm1"
          :rules="rules1"
          :model="diaLogForm1"
          label-width="85px"
        >
          <el-form-item label="项目名称" prop="project">
            <el-input
              v-model="diaLogForm1.project"
              size="small"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain size="mini" @click="Open1Submit"
          >确 认</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加2 -->
    <el-dialog
      v-loading="dialogLoading"
      :title="title2"
      :visible.sync="Open2"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="Open2Cancel"
    >
      <el-card>
        <el-form ref="diaLogForm1" :model="diaLogForm1" label-width="70px">
          <el-row>
            <el-col :span="12"
              ><el-form-item label="项目名称" prop="project">
                <el-input
                  v-model="diaLogForm1.project"
                  disabled
                  size="small"
                /> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" size="mini" @click="addRow" plain
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              @click="editRow"
              plain
              :disabled="single2"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              size="mini"
              @click="delRow"
              plain
              :disabled="multiple2"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              size="mini"
              @click="handleImport('projectMaintenance_detail')"
              >导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain size="mini" @click="handleExport2()"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5" style="float: right; margin-top: 10px">
            <el-input
              v-model="SearchText"
              placeholder="请输入关键字搜索"
              size="mini"
              clearable
              @input="intPutSearchText"
            ></el-input>
          </el-col>
        </el-row>
        <el-table
          ref="dialogData"
          :data="filterDialogData"
          border
          :max-height="THeight2"
          @selection-change="handleSelectionChange2"
          multiple
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center"
          />
          <el-table-column label="类型" align="center" prop="type1" />
          <el-table-column label="处置方式" align="center" prop="type2" />
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" plain size="mini" @click="Open2Cancel"
          >取 消</el-button
        >
        <el-button type="success" plain size="mini" @click="Open2Submit"
          >保 存</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加/编辑3 -->
    <el-dialog
      :title="title3"
      :visible.sync="Open3"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="Open3Cancel"
    >
      <el-card>
        <el-form
          ref="diaLogForm3"
          :rules="rules3"
          :model="diaLogForm3"
          label-width="85px"
        >
          <el-form-item label="类型" prop="type1">
            <el-select v-model="diaLogForm3.type1" size="small" filterable>
              <el-option
                v-for="item in Types"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处置方式" prop="type2">
            <el-input v-model="diaLogForm3.type2" size="small" />
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain size="mini" @click="Open3Submit"
          >确 认</el-button
        >
      </div>
    </el-dialog>
    <!-- 文件导入 -->
    <UploadExcel
      ref="child"
      :moban="moban"
      :relations="relations"
      @child-event="ImportFile"
    ></UploadExcel>
  </div>
</template>

<script>
import {
  reqGetActionType,
  reqInsertActionType,
  reqDeleteActionType,
  reqUdpateActionType,
} from "@/api/newApi/OCAP/index.js";
import XLSX from "xlsx";
import moment from "moment";
export default {
  components: {
    UploadExcel: () => import("@/views/components/uploadExcel"),
  },
  data() {
    return {
      THeight: undefined,
      THeight2: undefined,
      loading: false,
      dialogLoading: false,
      tableList: [],
      selection1: [],
      // 查询参数
      searchForm: {},
      Page: { pageNum: 1, pageSize: 20 },
      total: 0,
      rules1: {
        project: {
          required: true,
          message: "项目名称必填",
          trigger: "blur",
        },
      },
      rules3: {
        type1: {
          required: true,
          message: "类型必选",
          trigger: "blur",
        },
        type2: {
          required: true,
          message: "处置方式必填",
          trigger: "blur",
        },
      },
      Open1: false,
      Open2: false,
      Open3: false,
      title2: null,
      title3: null,
      // 表单参数
      diaLogForm1: {},
      diaLogForm3: {},
      // 非单个禁用
      single2: true,
      // 非多个禁用
      multiple1: true,
      multiple2: true,
      ids: [],
      Indexs: [],
      //处置方式
      project: null, //当前处理project
      dialogData: [], //表格数据
      filterDialogData: [], //过滤的表格数据
      Types: ["人", "机", "料", "法", "环"],
      SearchText: null,
      moban: null,
      fileList: [], //上传文件
      relations: {
        项目名称: "project",
      },
    };
  },
  computed: {},
  watch: {
    // 表格搜索框
    dialogData(newV, oldV) {
      this.filterDialogData = this.dialogData.filter(
        (data) =>
          !this.SearchText ||
          data.type1.toLowerCase().includes(this.SearchText.toLowerCase()) ||
          data.type2.toLowerCase().includes(this.SearchText.toLowerCase())
      );
    },
  },
  mounted() {
    this.THeight = (72 * window.innerHeight) / 100;
    this.THeight2 = (60 * window.innerHeight) / 100;
    this.getInfo();
  },
  methods: {
    //searchText改变
    intPutSearchText(val) {
      this.filterDialogData = this.dialogData.filter(
        (data) =>
          !val ||
          data.type1.toLowerCase().includes(val.toLowerCase()) ||
          data.type2.toLowerCase().includes(val.toLowerCase())
      );
    },
    //给数据加id,Index
    addIdIndex(resData) {
      this.tableList = resData.map((item, index) => {
        return {
          id: (this.Page.pageNum - 1) * this.Page.pageSize + index + 1,
          Index: (this.Page.pageNum - 1) * this.Page.pageSize + index + 1,
          ...item,
        };
      });
    },
    //获取数据
    async getInfo() {
      //前后去空格
      if (this.searchForm.project) {
        this.searchForm.project = this.searchForm.project.trim();
      }
      this.loading = true;
      let res = await reqGetActionType(
        Object.assign(this.searchForm, this.Page)
      );
      if (res.code == 0) {
        this.addIdIndex(res.data);
        this.total = res.total;
      } else {
        this.$modal.msgError(res.message);
      }
      this.loading = false;
    },
    handleSearch() {
      this.Page.pageNum = 1;
      this.getInfo();
    },
    // 重置
    handleReset() {
      this.searchForm = {};
      this.Page.pageNum = 1;
      this.getInfo();
    },
    handleAdd() {
      this.Open1 = true;
    },
    //维护详情
    SeeMaintence(row) {
      this.title2 = "维护详情";
      this.diaLogForm1 = { ...row };
      this.dialogData = JSON.parse(JSON.stringify(row.types));
      const order = ["人", "机", "料", "法", "环"];
      this.dialogData.sort((a, b) => {
        return order.indexOf(a.type1) - order.indexOf(b.type1);
      });
      this.project = row.project;
      this.Open2 = true;
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      this.selection1 = selection;
      this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
      this.Indexs = selection.map((item) => item.Index).sort((a, b) => b - a);
      this.multiple1 = !selection.length; // 非多个禁用
    },
    // 多选框选中数据
    handleSelectionChange2(selection) {
      this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
      this.single2 = selection.length != 1; // 非单个禁用
      this.multiple2 = !selection.length; // 非多个禁用
    },
    //添加行
    addRow() {
      //取消勾选
      for (let i = 0; i < this.ids.length; i++) {
        this.dialogData.forEach((item, index) => {
          if (item.id == this.ids[i]) {
            this.$refs.dialogData.toggleRowSelection(item, false);
          }
        });
      }
      this.title3 = "添加";
      this.diaLogForm3 = {};
      this.resetForm("diaLogForm3");
      this.Open3 = true;
      this.SearchText = null;
    },
    //编辑行
    editRow() {
      this.title3 = "修改";
      let oldDialogData = JSON.parse(JSON.stringify(this.dialogData)); //深拷贝
      oldDialogData.forEach((item) => {
        if (item.id == this.ids[0]) {
          this.diaLogForm3 = item;
        }
      });
      this.Open3 = true;
    },
    //删除行
    delRow() {
      for (let i = 0; i < this.ids.length; i++) {
        //删除行
        this.dialogData.forEach((item, index) => {
          if (item.id == this.ids[i]) {
            this.dialogData.splice(index, 1);
          }
        });
      }
      //重新排序
      this.dialogData.forEach((item, index) => {
        item.id = index;
      });
      //重新赋值
      this.dialogData = [...this.dialogData];
    },
    Open1Cancel() {
      this.resetForm("清除所有");
      this.resetForm("diaLogForm1");
      this.Open1 = false;
    },
    Open1Submit() {
      this.$refs["diaLogForm1"].validate((valid) => {
        if (valid) {
          //请求该设备是否已添加
          let reqForm = { ...this.diaLogForm1, types: [] };
          this.project = this.diaLogForm1.project.trim();
          reqInsertActionType(reqForm).then((res) => {
            if (res.code == 0) {
              this.$modal.msgSuccess("添加成功，请维护详细信息");
              this.title2 = "详细信息";
              this.Open2 = true;
              this.getInfo();
            } else if (res.code == 1) {
              this.$modal.msgError(res.msg);
            }
          });
        }
      });
    },
    //取消2
    Open2Cancel() {
      this.dialogData = [];
      this.resetForm("清除所有");
    },
    //提交2，发请求
    async Open2Submit() {
      let reqForm = {
        project: this.project,
        types: this.dialogData,
      };
      this.dialogLoading = true;
      let res = await reqUdpateActionType(reqForm);
      this.dialogLoading = false;
      if (res.code == 0) {
        this.$modal.msgSuccess("保存成功");
        this.resetForm("清除所有");
        this.getInfo();
      } else {
        this.$modal.msgError(res.msg);
      }
    },
    Open3Cancel() {
      this.Open3 = false;
    },
    //提交3，将数据保存到dialogData
    Open3Submit() {
      this.$refs["diaLogForm3"].validate((valid) => {
        if (valid) {
          if (this.title3 == "添加") {
            this.dialogData.push({
              id: this.dialogData.length,
              type1: this.diaLogForm3.type1,
              type2: this.diaLogForm3.type2,
            });
          } else if (this.title3 == "修改") {
            this.dialogData.forEach((item) => {
              if (item.id == this.ids[0]) {
                item.type1 = this.diaLogForm3.type1;
                item.type2 = this.diaLogForm3.type2;
              }
            });
          }
          this.Open3 = false;
        }
      });
    },
    //删除
    handleDel(row) {
      let delArr = [];
      let Indexs = [];
      if (row) {
        delArr = [{ project: row.project }];
        Indexs = row.Index;
      } else {
        for (let i = 0; i < this.selection1.length; i++) {
          delArr.push({
            project: this.selection1[i].project,
          });
        }
        Indexs = this.Indexs.sort((a, b) => a - b);
      }
      this.$modal
        .confirm('是否确认删除序号为"' + Indexs + '"的数据项？')
        .then(() => {
          return reqDeleteActionType(delArr);
        })
        .then((res) => {
          if (res.code == 0) {
            this.$modal.msgSuccess("删除成功");
            //最后一页只剩1条数据，删除后pageNum--
            if (this.tableList.length == 1 && this.Page.pageNum > 1) {
              this.Page.pageNum--;
            }
            this.getInfo();
          }
        })
        .catch(() => {});
    },
    resetForm(name) {
      if (name == "清除所有") {
        this.Open1 = false;
        this.Open2 = false;
        this.diaLogForm1 = {};
        this.diaLogForm3 = {};
        this.dialogData = [];
        this.SearchText = null;
      }
    },
    //导入
    handleImport(name) {
      this.moban = name;
      if (name == "projectMaintenance_detail") {
        this.relations = {
          类型: "type1",
          处置方式: "type2",
        };
      }
      this.$refs.child.dialogOpen();
    },
    ImportFile(reqArr, fileItem) {
      if (this.moban == "projectMaintenance") {
        //将reqArr数组中每个对象的属性的属性值都改为字符串类型
        for (let i = 0; i < reqArr.length; i++) {
          for (let key in reqArr[i]) {
            if (reqArr[i][key] !== null) {
              reqArr[i][key] = reqArr[i][key].toString();
            }
          }
        }
        Promise.all(reqArr.map((req) => reqInsertActionType(req)))
          .then((responses) => {
            const success = responses.every((response) => response.code === 0);
            if (success) {
              this.$modal.msgSuccess("导入成功");
              this.$refs.child.uploadCancel();
              this.getInfo();
            } else {
              //将失败的数据的索引存入数组
              let indexArr = [];
              responses.forEach((item, index) => {
                if (
                  item.code != 0 &&
                  item.msg == "该项目已添加，请勿重复添加"
                ) {
                  indexArr.push(index + 2);
                }
              });
              const Msg = `第${indexArr.toString()}行数据已存在，请勿重复添加`;
              this.$modal.msgError(Msg);
              this.getInfo();
            }
          })
          .catch((error) => {
            this.$modal.msgError("导入失败: " + error.message);
          });
      } else if ((this.moban = "projectMaintenance_detail")) {
        //如果this.dialogData中无reqArr中的数据，则将数据存入this.dialogData中
        // reqArr.forEach((item) => {
        //   if (
        //     !this.dialogData.some(
        //       (i) => i.type1 === item.type1 && i.type2 === item.type2
        //     )
        //   ) {
        //     let newItem = {
        //       id: this.dialogData.length + 1,
        //       ...item,
        //     };
        //     this.dialogData.push(newItem);
        //   }
        //   this.$refs.child.uploadCancel();
        // });
        reqArr.forEach((item) => {
          let newItem = {
            id: this.dialogData.length + 1,
            ...item,
          };
          this.dialogData.push(newItem);
          this.$refs.child.uploadCancel();
        });
      }
    },
    //导出
    async handleExport() {
      if (this.tableList.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: `Loading`,
          spinner: "el-icon-loading",
        });
        try {
          const headers = ["项目名称", "维护详情"];
          //前后去空格
          if (this.searchForm.project) {
            this.searchForm.project = this.searchForm.project.trim();
          }
          let Page = { pageSize: this.total, pageNum: 1 };
          let res = await reqGetActionType(
            Object.assign(this.searchForm, Page)
          );
          const datas = res.data.map((item) => [
            item.project,
            JSON.stringify(item.types),
          ]);
          const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
          XLSX.writeFile(
            workbook,
            `项目维护${moment(new Date()).format("yyyy-MM-DD HH:mm")}.xlsx`
          );
        } catch (error) {
          console.error("导出数据失败:", error);
        } finally {
          loading.close();
        }
      } else {
        this.$modal.msgError("暂无数据可导出");
      }
    },
    //导出
    async handleExport2() {
      if (this.dialogData.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: `Loading`,
          spinner: "el-icon-loading",
        });
        try {
          const headers = ["类型", "处置方式"];
          const datas = this.dialogData.map((item) => [item.type1, item.type2]);
          const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
          XLSX.writeFile(workbook, `${this.project}-维护详情.xlsx`);
        } catch (error) {
          console.error("导出数据失败:", error);
        } finally {
          loading.close();
        }
      } else {
        this.$modal.msgError("暂无数据可导出");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.service {
  padding: 0 20px;
}

::v-deep .el-input--small .el-input__inner {
  height: 30px !important;
  line-height: 30px !important;
}

::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #f0f8ff !important;
}

::v-deep .el-dialog__body {
  padding: 5px 20px !important;
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #515a6e !important;
}

::v-deep .box-card .el-form-item {
  margin-bottom: 2px !important;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>